const mysql = require('mysql');

const pool = mysql.createPool({
    host: 'localhost',
    user: 'root',
    password: 'root',
    database: 'mp4'
});

exports.query = function (sql, values) {
    // 返回一个新的 Promise
    return new Promise((resolve, reject) => {
        pool.getConnection(function (err, connection) {
            if (err) {
                console.log(err, "数据库连接失败");
                return reject({ code: 500, message: "数据库连接失败" });
            }
            
            connection.query(sql, values, (err, results) => {
                connection.release(); // 始终释放连接
                if (err) {
                    console.log(err, "查询数据库失败");
                    return reject({ code: 400, message: "查询数据库失败" });
                }
                // 在 Promise 中解决并返回查询结果
                resolve(results);
            });
        });
    });
};